package org.shj.spring.boot.lang;

import org.apache.commons.beanutils.ConvertUtils;
import org.shj.spring.boot.lang.exception.BeanMapperException;

/**
 * 简单封装Apache BeanUtils的ConvertUtils, 实现String<->Java Object的工具类.
 * 可转换的类型包括各种Primitives和Date。
 */
public class StringMapper {

    static {
        //装载BeanMapper类.
        BeanMapper.class.getClass();
    }

    /**
     * String->Object.
     *
     * @param value  待转换的字符串.
     * @param toType 转换目标类型.
     */
    public static <T> T fromString(String value, Class<T> toType) {
        try {
            return (T) ConvertUtils.convert(value, toType);
        } catch (Exception e) {
            throw new BeanMapperException(e);
        }
    }

    /**
     * Object -> String.
     */
    public static String toString(Object object) {
        try {
            return ConvertUtils.convert(object);
        } catch (Exception e) {
            throw new BeanMapperException(e);
        }
    }

}
